package com.koo.modules.sale.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.koo.common.constant.CodeConstant;
import com.koo.common.utils.*;
import com.koo.common.vo.AuditParams;
import com.koo.common.vo.AuditVo;
import com.koo.framework.feign.SystemFeignService;
import com.koo.modules.product.entity.ProductInfoEntity;
import com.koo.modules.product.service.ProductInfoService;
import com.koo.modules.purchase.entity.vo.PurchaseQueryVo;
import com.koo.modules.sale.dao.SaleAdjustPriceDao;
import com.koo.modules.sale.entity.SaleAdjustPriceDetailEntity;
import com.koo.modules.sale.entity.SaleAdjustPriceEntity;
import com.koo.modules.sale.service.SaleAdjustPriceDetailService;
import com.koo.modules.sale.service.SaleAdjustPriceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SaleAdjustPriceServiceImpl extends ServiceImpl<SaleAdjustPriceDao, SaleAdjustPriceEntity> implements SaleAdjustPriceService {

    @Autowired
    private SaleAdjustPriceDetailService adjustPriceDetailService;
    @Autowired
    private SystemFeignService systemFeignService;
    @Autowired
    private ProductInfoService productInfoService;
    
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<SaleAdjustPriceEntity> wrapper = new QueryWrapper<>();
        List<Long> ids = new ArrayList<>();
        boolean isItemQuery = false;

        Object dataForm = params.get("dataForm");
        if (dataForm != null) {
            PurchaseQueryVo queryVo = JSON.parseObject(dataForm + "", PurchaseQueryVo.class);
            String queryDates = queryVo.getQueryDates();
            Integer auditStatus = queryVo.getAuditStatus();
            String key = queryVo.getKey();
            String queryField = queryVo.getQueryField();
            String itemKey = queryVo.getItemKey();
            String queryItemField = queryVo.getQueryItemField();

            if (queryVo != null) {
                //子查询，获取明细ID
                if (MyStrUtil.isNotEmpty(itemKey) && MyStrUtil.isNotEmpty(queryItemField)) {
                    isItemQuery = true;
                    QueryWrapper<SaleAdjustPriceDetailEntity> itemWrapper = new QueryWrapper<>();
                    itemWrapper.like(queryItemField, itemKey);
                    List<SaleAdjustPriceDetailEntity> list = adjustPriceDetailService.list(itemWrapper);
                    if (CollectionUtils.isNotEmpty(list)) {
                        for (SaleAdjustPriceDetailEntity detailEntity : list) {
                            ids.add(detailEntity.getAdjustPriceId());
                        }
                    }
                }
                if (MyStrUtil.isNotEmpty(queryDates)) {
                    String[] queryDateArr = queryDates.split(",");
                    String startDate = queryDateArr[0];
                    String endDate = queryDateArr[1];
                    wrapper.ge(MyStrUtil.isNotEmpty(startDate), "adjust_price_date", startDate);
                    wrapper.le(MyStrUtil.isNotEmpty(endDate), "adjust_price_date", endDate);
                }
                wrapper.eq(auditStatus != null, "IFNULL(audit_status, 0)", auditStatus);
                wrapper.like(StringUtils.isNotBlank(queryField) && StringUtils.isNotBlank(key), queryField, key);
            }
        }

        IPage<SaleAdjustPriceEntity> page = new Query<SaleAdjustPriceEntity>().getPage(params);
        if (isItemQuery) {
            if(CollectionUtils.isNotEmpty(ids)){
                page = baseMapper.listPage(page, wrapper, ids);
            }
        } else {
            page = baseMapper.selectPage(page, wrapper);
        }
        return new PageUtils(page);
    }

    @Override
    public List<SaleAdjustPriceEntity> listByStoreId(Long storeId) {
        LambdaQueryWrapper<SaleAdjustPriceEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MyStrUtil.isNotEmpty(storeId), SaleAdjustPriceEntity::getStoreId, storeId);
        return this.list(wrapper);
    }

    @Override
    public SaleAdjustPriceEntity info(String adjustPriceId) {
        if(MyStrUtil.isNotEmpty(adjustPriceId)){
            SaleAdjustPriceEntity orderEntity = baseMapper.selectById(adjustPriceId);
            if(orderEntity != null){
                List<SaleAdjustPriceDetailEntity> itemEntities = adjustPriceDetailService.listByAdjustPriceId(adjustPriceId);
                orderEntity.setItemList(itemEntities);
            }
            return orderEntity;
        }
        return null;
    }

    @Override
    public void updateOrder(SaleAdjustPriceEntity adjustPriceEntity) {
        if (adjustPriceEntity != null) {
            //1、保存主单
            int res = baseMapper.updateById(adjustPriceEntity);
            //2、删除所有明细
            LambdaQueryWrapper<SaleAdjustPriceDetailEntity> qw = new LambdaQueryWrapper<>();
            qw.eq(adjustPriceEntity.getAdjustPriceId() != null, SaleAdjustPriceDetailEntity::getAdjustPriceId, adjustPriceEntity.getAdjustPriceId());
            boolean remove = adjustPriceDetailService.remove(qw);
            log.info("orderItemService.remove===", remove);
            //3、保存明细
            this.saveItemList(adjustPriceEntity);

        }
    }

    @Override
    public String getOrderNo() {
        return  CodeConstant.TJ + UserUtils.getStoreCode() + MyDateUtil.format(new Date(), "yyyyMMddHHmmss");
    }

    @Override
    public void saveOrder(SaleAdjustPriceEntity adjustPriceEntity) {
        int res = baseMapper.insert(adjustPriceEntity);

        this.saveItemList(adjustPriceEntity);

        //创建审核单
        Long adjustPriceId = adjustPriceEntity.getAdjustPriceId();

        AuditVo auditVo = new AuditVo();
        auditVo.setAuditStatus(0);
        auditVo.setUserId(adjustPriceEntity.getAuditUserId() + "");
        auditVo.setUserName(adjustPriceEntity.getAuditUser());
        auditVo.setOrderId(adjustPriceId);
        auditVo.setOrderNo(adjustPriceEntity.getAdjustPriceNo());
        auditVo.setTableName("sale_adjust_price");
        auditVo.setTitle("请审批调价单【" + adjustPriceEntity.getAdjustPriceNo() + "】");
        String s = systemFeignService.saveAduit(auditVo);
        log.info("saveOrder result===", s);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(AuditParams auditParams) {
        //1、修改表单审核状态
        if (auditParams != null && MyStrUtil.isNotEmpty(auditParams.getIds())) {
            String ids = auditParams.getIds();
            String[] idArr = ids.split(",");
            for (int i = 0; i < idArr.length; i++) {
                String id = idArr[i];
                SaleAdjustPriceEntity orderEntity = baseMapper.selectById(id);
                if (orderEntity != null) {
                    orderEntity.setAuditStatus(auditParams.getAuditStatus());
                    orderEntity.setAuditNote(auditParams.getAuditOptions());
                    baseMapper.updateById(orderEntity);
                }

                //2. //2、更新商品数据中的价格信息
                List<SaleAdjustPriceDetailEntity> orderItemList = adjustPriceDetailService.listByAdjustPriceId(id);
                if(CollectionUtils.isNotEmpty(orderItemList)){
                    orderItemList.stream().forEach(item -> {
                        ProductInfoEntity productInfo = new ProductInfoEntity();
                        BeanUtils.copyProperties(item, productInfo);
                        productInfo.setSalePrice(item.getNewSalePrice());
                        productInfo.setMemberPrice(item.getNewMemberPrice());
                        productInfoService.updateById(productInfo);
                    });
                }
            }

            //3、修改审核表状态
            auditParams.setTitle(auditParams.getAuditStatus() == 1 ? "已审核调价订单" : "审核不通过调价订单");
            String s = systemFeignService.updateAudit(auditParams);
            log.info("updateAudit result===", s);
        }
    }

    public void saveItemList(SaleAdjustPriceEntity adjustPriceEntity) {
        Long id = adjustPriceEntity.getAdjustPriceId();
        List<SaleAdjustPriceDetailEntity> itemList = adjustPriceEntity.getItemList();
        if (CollectionUtils.isNotEmpty(itemList)) {
            List<SaleAdjustPriceDetailEntity> collect = itemList.stream().filter(item -> {
                return MyStrUtil.isNotEmpty(item.getProductCode()) && item.getNewSalePrice().compareTo(new BigDecimal(0)) > 0;
            }).map(item -> {
                item.setDetailId(null);
                item.setAdjustPriceId(id);
                item.setAdjustPriceNo(adjustPriceEntity.getAdjustPriceNo());
                return item;
            }).collect(Collectors.toList());
            adjustPriceDetailService.saveBatch(collect);
        }
    }
}